package com.farm.model.product.controller;

import com.farm.config.exception.PageResult;
import com.farm.config.exception.Result;
import com.farm.config.exception.ResultCode;
import com.farm.config.exception.ResultGenerator;
import com.farm.model.product.entity.Product;
import com.farm.model.product.request.ProductRequest;
import com.farm.model.product.request.TaobaoPullRequest;
import com.farm.model.product.service.ProductService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@Controller
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    /**
     * 分页查询商品信息
     * @Author zhangBin
     * @Date 2018/10/30 15:57
     */
    @RequestMapping(value = "/pagedByProduct", method = RequestMethod.POST)
    @ResponseBody
    public PageResult pagedByProduct(@RequestBody ProductRequest productRequest) {
        PageHelper.startPage(productRequest.getPageNum().intValue(),productRequest.getPageSize().intValue());
        List<Product> productList = productService.pagedByProduct(productRequest);
        PageInfo<Product> pageInfo= new PageInfo<>(productList);
        PageResult result = new PageResult();
        result.setCode(ResultCode.SUCCESS.getCode());
        result.setMsg(ResultCode.SUCCESS.getMsg());
        result.setTotalSize(pageInfo.getTotal());
        result.setData(productList);
        return result;
    }

    /**
    *从淘宝添加产品
    *@Author ziming
    *@Date 2018/11/6 19:55
    */
    @PostMapping(value = "/addProduct")
    @ResponseBody
    public Result addProduct(@RequestBody TaobaoPullRequest taobaoPullRequest){
        if(Objects.isNull(taobaoPullRequest) || StringUtils.isBlank(taobaoPullRequest.getSearchName())){
            return ResultGenerator.genErrorResult(ResultCode.PARAM_ERROR.getCode(),ResultCode.PARAM_ERROR.getMsg());
        }
        productService.addProductToTaobao(taobaoPullRequest);
        return  ResultGenerator.genSuccessResult();
    }

}
